package feifei.cookiezuoye;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/servlet1.action")
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;chatset=utf-8");

        Cookie[] cookies = req.getCookies();
        String value = (String) req.getAttribute("username");
//        Cookie[] cookies = (Cookie[]) req.getAttribute("cookies");
        boolean cookieExists = false;

        System.out.println("测试一下是否进来servlet1");
        if(cookies!=null){
            if(cookies.length!=0){
                for (Cookie cookie : cookies) {
                    System.out.println("进入循环，cookie不为空");
                    if (cookie.getName().equals("username")) {
                        value = cookie.getValue();
                        System.out.println("user的值为"+value);
                        cookieExists = true;
                        break;
                    }
                }
            }
        }
        if(value!=null||cookieExists){
            resp.getWriter().write(value+"我欢迎你");
        }else{
                req.getRequestDispatcher("/login.html").forward(req,resp);
//            resp.sendRedirect("/day32/login.html");
            }
        }
}
